<template>
  <div>
    <el-card shadow="hover" style="margin-bottom: 10px">
      <div slot="header" class="clearfix">
        <span>PLC与货架绑定关系</span>
        <el-button type="primary" size="mini" style="float: right" @click="handleAdd">
          <i class="el-icon-plus"></i> 添加绑定
        </el-button>
      </div>
      <el-table v-loading="loading" :data="bindingList" style="width: 100%">
        <el-table-column prop="id" label="绑定ID" width="80" fixed="left"></el-table-column>
        <el-table-column prop="plcId" label="PLC ID" width="100"></el-table-column>
        <el-table-column prop="shelfId" label="货架ID" width="100"></el-table-column>
        <el-table-column prop="plcMemoryAddr" label="PLC内存地址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creator_Name" label="创建人" width="150"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加绑定弹窗 -->
    <el-dialog title="添加绑定" :visible.sync="dialogVisible" width="500px" @close="handleCloseDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="PLC ID" prop="plcId">
          <el-input v-model.number="form.plcId" placeholder="请输入PLC ID" type="number"></el-input>
        </el-form-item>
        <el-form-item label="货架ID" prop="shelfId">
          <el-input v-model.number="form.shelfId" placeholder="请输入货架ID" type="number"></el-input>
        </el-form-item>
        <el-form-item label="PLC内存地址" prop="plcMemoryAddr">
          <el-input v-model="form.plcMemoryAddr" placeholder="例如：M1, D100"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import shelfApi from '@/api/shelf'

export default {
  name: 'DeviceBinding',
  data() {
    return {
      loading: false,
      submitLoading: false,
      bindingList: [],
      dialogVisible: false,
      form: {
        plcId: null,
        shelfId: null,
        plcMemoryAddr: ''
      },
      rules: {
        plcId: [
          { required: true, message: '请输入PLC ID', trigger: 'blur' },
          { type: 'number', message: 'PLC ID必须为数字', trigger: 'blur' }
        ],
        shelfId: [
          { required: true, message: '请输入货架ID', trigger: 'blur' },
          { type: 'number', message: '货架ID必须为数字', trigger: 'blur' }
        ],
        plcMemoryAddr: [
          { required: true, message: '请输入PLC内存地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchBindingList()
  },
  methods: {
    async fetchBindingList() {
      this.loading = true
      try {
        const res = await shelfApi.getShelfPlcBindingList()
        const body = res.data

        if (body.code === 200 && body.data && body.data.plcList) {
          this.bindingList = body.data.plcList || []
        } else {
          this.bindingList = []
          this.$message.error(body.message || '获取绑定列表失败')
        }
      } catch (error) {
        this.bindingList = []
        console.error('获取绑定列表失败:', error)
        this.$message.error('获取绑定列表失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    formatDateTime(row, column, cellValue) {
      if (!cellValue) return ''
      return new Date(cellValue).toLocaleString()
    },
    resetForm() {
      this.form = {
        plcId: null,
        shelfId: null,
        plcMemoryAddr: ''
      }
    },
    handleCloseDialog() {
      this.$refs.form.clearValidate()
      this.resetForm()
    },
    handleAdd() {
      this.resetForm()
      this.dialogVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            // The API requires a 'creator' field.
            // This should be replaced with the actual logged-in user's ID.
            const payload = {
              ...this.form,
              creator: 1 // Using a placeholder ID
            }
            await shelfApi.addShelfPlcBinding(payload)
            this.$message.success('添加成功')
            this.dialogVisible = false
            this.fetchBindingList()
          } catch (error) {
            console.error('操作失败:', error)
            const errorMessage = error.response?.data?.message || '操作失败'
            this.$message.error(errorMessage)
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    handleDelete(bindingId) {
      this.$confirm('确定要删除该条绑定关系吗？此操作不可撤销。', '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await shelfApi.deleteShelfPlcBinding(bindingId)
          this.$message.success('删除成功')
          this.fetchBindingList()
        } catch (error) {
          console.error('删除绑定失败:', error)
          const errorMessage = error.response?.data?.message || '删除失败'
          this.$message.error(errorMessage)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
